<?php

namespace App\Observers;

use App\Models\User;
use App\Services\LogService;
use App\Services\CacheService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Hash;

class UserObserver
{
    protected LogService $logService;
    protected CacheService $cacheService;

    public function __construct(LogService $logService, CacheService $cacheService)
    {
        $this->logService = $logService;
        $this->cacheService = $cacheService;
    }

    /**
     * Handle the User "creating" event.
     */
    public function creating(User $user): void
    {
        // 用户创建时的日志记录
        // 密码加密由控制器负责，这里不再处理
    }

    /**
     * Handle the User "created" event.
     */
    public function created(User $user): void
    {
        $this->logService->logUserAction('registered', [
            'user_id' => $user->id,
            'email' => $user->email,
            'name' => $user->name,
        ]);
        
        Log::info('User registered', [
            'user_id' => $user->id,
            'email' => $user->email,
            'name' => $user->name,
        ]);
    }

    /**
     * Handle the User "updated" event.
     */
    public function updated(User $user): void
    {
        // 检查密码是否发生变化
        if ($user->isDirty('password')) {
            $this->logService->logSecurity('password_changed', [
                'user_id' => $user->id,
                'email' => $user->email,
            ]);

            Log::info('User password changed', [
                'user_id' => $user->id,
                'email' => $user->email,
            ]);
        }

        // 检查邮箱是否发生变化
        if ($user->isDirty('email')) {
            $oldEmail = $user->getOriginal('email');
            $newEmail = $user->email;
            
            $this->logService->logSecurity('email_changed', [
                'user_id' => $user->id,
                'old_email' => $oldEmail,
                'new_email' => $newEmail,
            ]);

            Log::info('User email changed', [
                'user_id' => $user->id,
                'old_email' => $oldEmail,
                'new_email' => $newEmail,
            ]);
        }

        // 检查状态是否发生变化
        if ($user->isDirty('is_active')) {
            $oldStatus = $user->getOriginal('is_active');
            $newStatus = $user->is_active;
            
            $this->logService->logUserAction('status_changed', [
                'user_id' => $user->id,
                'email' => $user->email,
                'old_status' => $oldStatus ? 'active' : 'inactive',
                'new_status' => $newStatus ? 'active' : 'inactive',
            ]);

            Log::info('User status changed', [
                'user_id' => $user->id,
                'email' => $user->email,
                'old_status' => $oldStatus ? 'active' : 'inactive',
                'new_status' => $newStatus ? 'active' : 'inactive',
            ]);
        }

        $this->logService->logUserAction('updated', [
            'user_id' => $user->id,
            'email' => $user->email,
        ]);

        // 清除用户缓存
        $this->clearUserCaches($user);
    }

    /**
     * Handle the User "deleted" event.
     */
    public function deleted(User $user): void
    {
        $this->logService->logUserAction('deleted', [
            'user_id' => $user->id,
            'email' => $user->email,
        ]);
        
        // 清除用户缓存
        $this->clearUserCaches($user);
        
        Log::info('User deleted', [
            'user_id' => $user->id,
            'email' => $user->email,
        ]);
    }

    /**
     * Handle the User "restored" event.
     */
    public function restored(User $user): void
    {
        $this->logService->logUserAction('restored', [
            'user_id' => $user->id,
            'email' => $user->email,
        ]);
        
        Log::info('User restored', [
            'user_id' => $user->id,
            'email' => $user->email,
        ]);
    }

    /**
     * Handle the User "force deleted" event.
     */
    public function forceDeleted(User $user): void
    {
        $this->logService->logUserAction('force_deleted', [
            'user_id' => $user->id,
            'email' => $user->email,
        ]);
        
        Log::info('User force deleted', [
            'user_id' => $user->id,
            'email' => $user->email,
        ]);
    }

    /**
     * 清除用户相关缓存
     */
    protected function clearUserCaches(User $user): void
    {
        try {
            $this->cacheService->forgetUser($user->id);
            
            Log::debug('User caches cleared', [
                'user_id' => $user->id,
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to clear user caches', [
                'user_id' => $user->id,
                'error' => $e->getMessage(),
            ]);
        }
    }
}
